﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Timers;
using System.Threading;
using System.IO;
using DauGiaApp.Models;
using System.Collections.Generic;
namespace DauGiaApp.Controllers
{
    public class Task
    {
        public  DauGiaEntities data = new DauGiaEntities();
        #region Fields

        System.Timers.Timer timer = null;

        #endregion

        #region Properties

        public string Name { get; set; }

        public bool IsRunning { get; set; }

        public DateTime LastRunTime { get; set; }

        public bool IsLastRunSuccessful { get; set; }

        public double Interval { get; set; }

        public bool Stopped { get; set; }

        public string FilePath { get; set; }

        #endregion

        #region Public Constructors

        public Task(double interval)
        {
            this.Interval = interval;
            Initialize();
        }

        #endregion

        #region Public Methods

        public void Start()
        {
            this.Stopped = false;
            this.StartTask();
        }

        public void Stop()
        {
            this.Stopped = true;
        }

        #endregion

        #region Private Methods

        private void Initialize()
        {
            this.Stopped = false;

            timer = new System.Timers.Timer(this.Interval);
            timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
            timer.Enabled = true;
        }

        private void StartTask()
        {
            if (!this.Stopped)
            {
                Thread thread = new Thread(new ThreadStart(Execute));
                thread.Start();
            }
        }

        private void Execute()
        {
            if (dangLam == true)
                return;
            dangLam = true;
            try
            {
                this.IsRunning = true;
                // dang cac phien dau gia dang cho
                DangPhienDauGiaDangCho();
                HoanThanhPhienDauGia();
                this.IsLastRunSuccessful = true;
            }
            catch
            {
                this.IsLastRunSuccessful = false;
                // Handle the exception
            }
            finally
            {
                dangLam = false;
                this.IsRunning = false;
                
            }
            dangLam = false;
        }

        void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            if (!this.IsRunning)
                StartTask();
        }

        #endregion


        public void DangPhienDauGiaDangCho()
        {
            // lay ra sp dang cho dau gia' da bat dau toi phien dau gia
            try
            {
                List<SanPham> spQueue = data.SanPhams
                                              .Where(sp => (int)sp.MaTinhTrangSanPham == 1
                                                      && DateTime.Now.CompareTo(sp.NgayHetHan) >= 0)
                                               .ToList();

                foreach (SanPham sp in spQueue)
                {
                    DauGia dg = new DauGia();
                    dg.SanPham = sp;
                    dg.ThoiGianBatDau = (DateTime)sp.NgayHetHan;

                    DateTime dt = DateTime.Now;
                    DateTime tgkt = dt.AddMinutes(5);
                    decimal giaKhoiDiem = (sp.GiaKhoiDiem != null)? (decimal)sp.GiaKhoiDiem : 0;
                    dg.ThoiGianKetThuc = tgkt;
                    dg.GiaKhopLenh = giaKhoiDiem;
                    data.DauGias.AddObject(dg);
                    sp.MaTinhTrangSanPham = 2; // dang dau gia
                    data.SaveChanges();
                }

            }
            catch (Exception ex)
            {
                System.Console.Write(ex.Message);
            }

        }

        public static bool dangLam = false;
        public void HoanThanhPhienDauGia()
        {
           
            try
            {
                // danh sach dau gia ket thuc phien
                List<DauGia> lsdg = data
                                    .DauGias
                                    .Where(dg => dg.SanPham.MaTinhTrangSanPham == 2
                                           && dg.ThoiGianKetThuc.CompareTo(DateTime.Now) < 0)
                                    .ToList();
                foreach(DauGia dg in lsdg)
                {
                    dg.SanPham.MaTinhTrangSanPham = 3;
                    List<ChiTietDauGia> lsctdg = dg
                                        .ChiTietDauGias
                                        .OrderByDescending(tmp => tmp.GiaGiaoDich)
                                        .ToList();
                    if (lsctdg.Count > 0) // sp co nguoi dau gia
                    {
                        ChiTietDauGia ctdg = lsctdg.ElementAt(0);
                        TaiKhoan tkThang = ctdg.TaiKhoan;
                        dg.TaiKhoan = tkThang;
                        dg.GiaKhopLenh = ctdg.GiaGiaoDich;
                        data.SaveChanges();
                    }
                    
                }
                data.SaveChanges();
            }
            catch (Exception ex)
            {
                
            }
            
        }
                
    }

}
